package com.motorola.dp.jenkinsmonitor.service.util.dom.xpath;

import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("xpathExpressionCache")
public class DefaultXpathExpressionCache implements XpathExpressionCache {

    @Value("#{T(javax.xml.xpath.XPathFactory).newInstance().newXPath()}")
    private XPath xpath;

    @Value("#{new java.util.HashMap()}")
    private Map<String, XPathExpression> cache;

    public XPathExpression lookup(String expression) throws XPathExpressionException {
        XPathExpression xpathExpr = cache.get(expression);
        if (xpathExpr == null) {
            xpathExpr = xpath.compile(expression);
            cache.put(expression, xpathExpr);
        }
        return xpathExpr;
    }

    public void setXpath(XPath xpath) {
        this.xpath = xpath;
    }

    public void setCache(Map<String, XPathExpression> cache) {
        this.cache = cache;
    }

}
